<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中...">
    <div class="content">
      <div class="text_print">
        <div> 名称：<el-input v-model="headerForm.name" class="page_num" /> </div>
        <div class="mod_cont">
          <div class="input_mm">
            纸张尺寸:
            <el-input-number
              :controls="false"
              v-model="headerForm.width"
              @change="changeNum($event, 1)"
              class="page_num2"
            />
            X
            <el-input-number
              :controls="false"
              v-model="headerForm.height"
              class="page_num2"
              @change="changeNum($event, 2)"
            />
          </div>
          <div class="input_mm">
            单码打印数量:
            <el-input-number
              :controls="false"
              v-model="headerForm.codeNum"
              class="page_num2"
              :min="1"
              @change="changeTotal"
            />
          </div>
          <!-- <div class="input_mm">
            纸张间距: <el-input-number :controls="false" v-model="headerForm.space" class="page_num2"
              @change="changeNum($event, 4)" />
          </div> -->
          <div class="input_mm">
            <el-tooltip
              :disabled="disabled"
              content="单行模版数量"
              placement="bottom"
              effect="light"
            >
              单行排列数量: </el-tooltip
            ><el-input-number
              :controls="false"
              :min="1"
              v-model="headerForm.rowQty"
              class="page_num2"
              @change="changeNum($event, 5)"
            />
          </div>
          <el-switch v-model="headerForm.status" active-text="启用" />
        </div>
        <div class="btns" style="display: flex; gap: 5px">
          <HPlainButton @click="onPreview">预览</HPlainButton>
          <HPlainButton @click="btnSave">保存</HPlainButton>
          <HButton @click="backPage">取消</HButton>
          <HPlainButton @click="delTemplate" v-if="paramsId.length > 1" type="error"
            >删除</HPlainButton
          >
        </div>
      </div>
    </div>
    <div class="print_code">
      <div class="left">
        <header class="header_top">
          <div class="text">组件</div>
          <el-icon @click="add(1)">
            <Grid />
          </el-icon>
          <el-icon @click="add(2)">
            <PictureFilled />
          </el-icon>
          <b @click="add(3)">T</b>
        </header>
        <div class="text_bb" style="display: flex; justify-content: space-between">
          <HPlainButton
            v-if="!show_module"
            :height="20"
            :padding-lr="6"
            @click="addcomponenTemplate"
            >添加组件模版</HPlainButton
          >
          <div class="b_title" v-if="show_module">
            <span>属性</span>
            <span>{{ list_type }}</span>
          </div>
          <HPlainButton
            :height="20"
            :padding-lr="6"
            v-if="show_module"
            @click="show_module = false"
          >
            组件列表
          </HPlainButton>
        </div>
        <el-menu
          :unique-opened="true"
          v-if="!show_module"
          ref="menu"
          :default-openeds="[boxIndex.toString()]"
        >
          <el-sub-menu
            v-for="(items, index) in componenTemplate"
            :key="index"
            :class="boxIndex == index ? 'isactive' : ''"
            @click="clickActive(index)"
            :index="index.toString()"
          >
            <template #title>
              <div class="com_li_left">
                <span class="name_edit">{{ items.name }}</span>
                <el-icon size="14px" @click.stop="editName(index, items.name)" class="edit_icon">
                  <EditPen />
                </el-icon>
              </div>
              <div class="com_li_right">
                <el-icon
                  class="delete_icon"
                  color="#f56c6c"
                  size="16px"
                  v-if="componenTemplate.length > 1"
                  @click.stop="removecomponenTemplate(index)"
                >
                  <RemoveFilled />
                </el-icon>
              </div>
            </template>
            <el-menu-item index="1-1" v-for="(item, index) in items.components" :key="index">
              <div class="text_name">{{ index + 1 + item.name }}</div>
              <div class="btn_code">
                <div class="del_edi_btn" @click="deleteBtn(index)">删除</div>
                <div class="del_edi_btn" @click="editBtn(item.type, index)">编辑</div>
              </div>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
        <div v-else class="details_mo">
          <HPlainButton type="error" :padding-lr="6" :height="20" @click="deleteBtn(null)"
            >删除组件</HPlainButton
          >
          <template v-for="(list_item, ind) in componenTemplate[boxIndex]?.components">
            <CodeModule
              v-if="ind == listArr_index"
              :mm_px="mm_px"
              :list_item="list_item"
              :list_type="list_type"
              @set-parent="componenTemplate[boxIndex].components[listArr_index] = $event"
              :key="ind"
            />
          </template>
        </div>
      </div>
      <div class="right" @mousedown.stop="clearSelect">
        <div class="big">
          <div class="main">
            <div
              class="cont apacerow"
              v-for="(item, index) in componenTemplate"
              :key="index"
              @mousedown.stop="selectBox($event, index)"
              :class="{ boxcolor: boxIndex == index }"
              draggable="true"
              @dragenter="dragenter($event, index)"
              @dragover="dragover($event)"
              @dragstart="dragstart(index)"
              :style="{
                height: headerForm.height + 'mm',
                width: headerForm.width + 'mm',
                margin: headerForm.paperSpacing + 'mm',
                position: 'relative',
              }"
            >
              <template v-for="(i, index2) in item.components" :key="index2">
                <!-- 编码 -->
                <div
                  @mousedown="move($event, index2, i.type)"
                  ref="elemDom"
                  :class="{ boxcolor: listArr_index == index2 && boxIndex == index }"
                  :style="{
                    position: 'absolute',
                    width: i.width + 'px',
                    height: i.height + 'px',
                    transform: 'rotate(' + i.rotateAngle + 'deg)',
                    left: i.coordinateX + 'px',
                    top: i.coordinateY + 'px',
                  }"
                >
                  <!-- 二维码 -->
                  <vue-qr
                    :qid="`id${index}${index2}`"
                    :style="{ width: i.width + 'px', height: i.height + 'px' }"
                    text="预览模版！"
                    :bindElement="true"
                    v-if="i.type == 1 && i.codeType == 1"
                    :margin="0"
                    :logoMargin="0"
                    :callback="test"
                    :logoCornerRadius="0"
                    :size="i.width"
                    :logoSrc="i.image"
                  ></vue-qr>
                  <!-- 图片 -->
                  <el-image
                    fit="scale-down"
                    :src="i.image"
                    v-if="i.type == 2"
                    :style="{ width: i.width + 'px', height: i.height + 'px' }"
                  >
                    <template #error>
                      <div class="image-slot_xy">
                        <el-icon><icon-picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <!-- 文字 -->
                  <template v-for="(it, itIndex) in i.dataTypeVos" :key="itIndex">
                    <div
                      v-if="i.type == 3"
                      :style="{
                        overflow: 'hidden',
                        width: i.width + 'px',
                        height: i.height + 'px',
                        fontSize: i.textWordSize + 'px',
                        fontFamily:
                          i.textFont == 1
                            ? '微软雅黑'
                            : i.textFont == 2
                            ? '黑体'
                            : i.textFont == 3
                            ? '宋体'
                            : i.textFont == 4
                            ? '楷体'
                            : i.textFont == 5
                            ? '隶书'
                            : i.textFont == 6
                            ? '幼圆'
                            : '仿宋',
                        lineHeight: i.textRowHeight + 'px',
                        color: i.textColor,
                        textAlign:
                          i.textAlign == 1 ? 'left' : i.textAlign == 2 ? 'center' : 'right',
                        fontWeight: i.textBold ? 'bold' : 'lighter',
                        textDecoration: i.textUnderline ? 'underline' : '',
                        fontStyle: i.textIncline ? 'italic' : '',
                        textIndent: i.textIndent + 'px',
                        letterSpacing: i.textSpacing + 'px',
                      }"
                    >
                      {{
                        it.category == 2
                          ? it.val
                          : it.category == 1
                          ? category2[it.category - 1]
                          : it.category == 3
                          ? category2[it.category - 1]
                          : it.category == 4
                          ? category2[it.category - 1]
                          : it.category == 5
                          ? category2[it.category - 1]
                          : it.category == 6
                          ? category2[it.category - 1]
                          : it.category == 7
                          ? category2[it.category - 1]
                          : it.category == 8
                          ? category2[it.category - 1]
                          : it.category == 9
                          ? category2[it.category - 1]
                          : it.category == 10
                          ? category2[it.category - 1]
                          : it.category == 11
                          ? category2[it.category - 1]
                          : category2[it.category - 1]
                      }}
                    </div>
                  </template>
                </div>
                <!-- 条形码 -->
                <div
                  :style="{
                    overflow: 'hidden',
                    width: i.width + 'px',
                    height: i.height + 'px',
                    position: 'absolute',
                    transform: 'rotate(' + i.rotateAngle + 'deg)',
                    left: i.coordinateX + 'px',
                    top: i.coordinateY + 'px',
                  }"
                  :class="{ boxcolor: listArr_index == index2 && boxIndex == index }"
                  @mousedown="move($event, index2, i.type)"
                  ref="elemDom"
                >
                  <BarcodeImg
                    v-if="i.type == 1 && i.codeType == 2"
                    :index="index"
                    :index2="index2"
                  ></BarcodeImg>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      :draggable="true"
      :align-center="true"
      width="30%"
    >
      <span style="text-align: center">是否删除？</span>
      <template #footer>
        <span class="dialog-footer">
          <HPlainButton is-modal type="error" @click="deleteZj"> 删除 </HPlainButton>
          <HButton is-modal @click="dialogVisible = false">取消</HButton>
        </span>
      </template>
    </el-dialog>
    <HModal v-model="editDialogVisible" title="修改组件模块名称" size="small">
      <div class="edit_name">
        <span style="white-space: nowrap">组件模块名称</span>
        <el-input
          v-model="editDialogName"
          class="input_edit"
          clearable
          placeholder="组件模块名称"
        />
      </div>
      <template #footerRight>
        <HButton type="primary" is-modal @click="onSaveEdit">保存</HButton>
        <HButton is-modal @click="editDialogVisible = false">取消</HButton>
      </template>
    </HModal>
    <!-- 预览 -->
    <el-dialog v-model="lookShow" title="预览" width="76%" class="lookshow" draggable>
      <div style="overflow: auto; height: 660px; background-color: #f1f1f1; padding: 14px">
        <div class="bg_card">
          <templateMain :itemData="templateDataList"> </templateMain>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue'
  import { storeToRefs } from 'pinia'
  import { useCodeState } from './../../../../store/modules/code'
  import CodeModule from '@/views/code/online/module/codeModule.vue'
  import templateMain from './templateMain.vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { codeUpload, deleteFile } from '../../../../api/upload'
  import vueQr from 'vue-qr/src/packages/vue-qr.vue'
  import BarcodeImg from './jsBarcode.vue'
  import * as _ from 'lodash'
  import {
    savePrintTemplate,
    printTemplateGetDetail,
    deletePrintTemplate,
  } from '../../../../api/code'
  import {
    EditPen,
    Grid,
    Picture as IconPicture,
    PictureFilled,
    RemoveFilled,
  } from '@element-plus/icons-vue'
  import { useSettingStore } from '../../../../store/modules/setting'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.snCode.emptyTemplateCreate,
  })

  const router = useRouter()
  const route = useRoute()
  const useSetting = useSettingStore()
  const editDialogVisible = ref(false)
  const editDialogName = ref()
  const editIndex = ref()
  const codeStore = useCodeState()
  const list_type = ref('')
  const show_module = ref(false) //显示编辑
  const dragIndex = ref()
  const boxIndex = ref(0)
  const mm_px = ref(1)
  const getImageUrl = ref()
  const dialogVisible = ref(false)
  const disabled = ref(false)
  const elemDom = ref()
  const menu = ref()
  const loading = ref(false)
  const { listArr_index, headerForm, imgListDelete } = storeToRefs(codeStore)
  const templateDataList = ref(null)
  const TagsViewStore = useTagsViewStore()
  const category2 = ref([
    '序号',
    '固定值',
    '防伪编码',
    '仓储编码',
    '品牌名称',
    '产品名称',
    '产品型号',
    '产品分类',
    '产品规格',
    '产品生产日期',
    '编码注册日期',
    '编码质保周期',
  ])
  const item1 = ref({
    type: 1, // 组件类型：1-编码组件，2-图片组件，3-文本组件，
    name: '编码组件', // 组件名称
    width: 45, // 宽度
    height: 45,
    lockScale: false, // 锁定比例：false-不锁定，true-锁定
    scaleSize: 1, //锁定比例大小
    coordinateX: 0, // 坐标X
    coordinateY: 0, // 坐标Y
    rotateAngle: 0, // 旋转角度
    codeType: 1, // 编码类型: 1-二维码，2-一维码
    dataTypeVos: [
      // 调用数据
      {
        category: 1, // 类型：1-固定值，2-防伪编码，3-仓储编码，4-防伪链接，5-产品展示链接；（注：当codeType=1时，4、5才显示）
        val: '',
      },
    ],
    image: '', // 美化图片路径，当codeType=2时，该字段生效
    tmpImg: '',
    textAlign: 1,
    textBold: false,
    textFont: 1,
    textIncline: false,
    textUnderline: false,
    textWordSize: '0',
    textSpacing: 0,
    textRowHeight: 16,
    textIndent: 0,
    textColor: ' ',
  })
  const item2 = ref({
    type: 2,
    name: '图片组件',
    width: 45,
    height: 45,
    lockScale: false,
    scaleSize: 1, //锁定比例大小
    coordinateX: 0,
    coordinateY: 0,
    rotateAngle: 0,
    image: '',
    tmpImg: '',
    codeType: 1,
    textAlign: 1,
    textBold: false,
    textFont: 1,
    textIncline: false,
    textUnderline: false,
    textWordSize: '0',
    textSpacing: 0,
    textRowHeight: 16,
    textIndent: 0,
    textColor: 1,
  })
  const item3 = ref({
    type: 3,
    name: '文本组件',
    width: 45,
    height: 16,
    lockScale: false,
    scaleSize: 1, //锁定比例大小
    coordinateX: 0,
    coordinateY: 0,
    rotateAngle: 0,
    dataTypeVos: [
      {
        category: 2,
        val: '文本',
        isShow: false,
      },
    ],
    textFont: 1,
    textWordSize: 14,
    textRowHeight: 16,
    textIndent: 0,
    textSpacing: 0,
    textAlign: 1,
    textBold: false,
    textIncline: false,
    textUnderline: false,
    textColor: '#000000',
    codeType: 1,
  })
  // 组件模版
  const componenTemplate = ref([
    {
      id: '',
      name: '组件模版_1',
      components: [],
    },
  ])
  const coun = ref(1)
  // 添加组件模版
  const addcomponenTemplate = () => {
    if (componenTemplate.value.length + 1 > 10) {
      ElMessage({
        showClose: true,
        message: '最多10个组件模版!',
        duration: 5000,
        offset: 200,
      })
      return
    }
    coun.value = componenTemplate.value.length + 1
    componenTemplate.value.push({
      id: '',
      name: '组件模版_' + coun.value,
      components: [],
    })
  }
  const backPage = () => {
    TagsViewStore.delView(router.currentRoute.value.path)
    router.back()
  }
  // 删除组件模版
  const removecomponenTemplate = (index: number) => {
    ElMessageBox.confirm('确定删除组件模块吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      autofocus: false,
    }).then(() => {
      componenTemplate.value = componenTemplate.value.filter((o, i) => {
        if (i == index && o.id.length > 1) {
          if (!headerForm.value.delTemplateComponentIds) {
            headerForm.value.delTemplateComponentIds = []
          }
          headerForm.value.delTemplateComponentIds.push(o.id)
          o.components.filter((j) => {
            if (j.type == 1 || j.type == 2) {
              if (j.image.length > 1) {
                imgListDelete.value.push(j.image)
              }
            }
          })
        }
        return i != index
      })
      ElMessage({
        type: 'success',
        message: '删除成功！',
        offset: 200,
        duration: 4000,
      })
    })
  }
  // 编辑组件模块名称
  const editName = (index: any, name: any) => {
    editDialogVisible.value = true
    editDialogName.value = name
    editIndex.value = index
  }
  // 预览
  const lookShow = ref(false)
  const onPreview = () => {
    lookShow.value = true
    templateDataList.value = JSON.parse(
      JSON.stringify({
        ...headerForm.value,
        templateComponentVos: componenTemplate.value.slice(0, 4),
      }),
    )
  }
  // 点击列表时
  const clickActive = (val: number) => {
    boxIndex.value = val
  }
  const onSaveEdit = () => {
    if (editDialogName.value == '') {
      ElMessage({
        showClose: true,
        message: '不能为空！',
        type: 'error',
        duration: 5000,
        offset: 200,
      })
      return
    }
    componenTemplate.value[editIndex.value].name = editDialogName.value
    editDialogVisible.value = false
    ElMessage({
      showClose: true,
      message: '修改成功！',
      type: 'success',
      duration: 5000,
      offset: 200,
    })
  }
  // 二维码
  const test = (dataUrl: any) => {
    getImageUrl.value = dataUrl
  }
  const dragenter = (e: { preventDefault: () => void }, index) => {
    e.preventDefault()
    if (dragIndex.value !== index) {
      const moving = componenTemplate.value[dragIndex.value]
      componenTemplate.value.splice(Number(dragIndex.value), 1)
      componenTemplate.value.splice(index, 0, moving)
      // 排序变化后目标对象的索引变成源对象的索引
      dragIndex.value = index
    }
  }
  const dragover = (e: { preventDefault: () => void }) => {
    e.preventDefault()
  }
  const dragstart = (index: any) => {
    dragIndex.value = index
  }
  const delTemplate = () => {
    if (headerForm.value.id.length > 1) {
      deletePrintTemplate([headerForm.value.id]).then((res) => {
        if (res.data.success) {
          componenTemplate.value.filter((o) => {
            o.components.filter((j) => {
              if (j.image.length > 0) {
                imgListDelete.value.push(j.image)
              }
            })
          })
          if (imgListDelete.value.length > 0) {
            deleteFile(imgListDelete.value)
          }
          ElMessage({
            type: 'success',
            showClose: true,
            message: res.data.message,
            duration: 5000,
          })
          router.back()
        } else {
          if (res.data.isError)
            if (res.data.isError)
              ElMessage({
                type: 'error',
                showClose: true,
                message: res.data.message,
                duration: 5000,
              })
        }
      })
    }
  }
  const deleteZj = () => {
    dialogVisible.value = false
    show_module.value = false
    componenTemplate.value[boxIndex.value].components = componenTemplate.value[
      boxIndex.value
    ].components.filter((o, index) => {
      if (index == listArr_index.value) {
        if (o.id) {
          if (!headerForm.value.delTemplateComponentIds) {
            headerForm.value.delTemplateComponentIds = []
          }
          headerForm.value.delTemplateComponentIds.push(o.id)
          if (o.type == 1 || o.type == 2) {
            if (o.image.length > 0) {
              imgListDelete.value.push(o.image)
            }
          }
        }
      }
      return index != listArr_index.value
    })
  }
  const deleteBtn = (index: number) => {
    if (index) {
      listArr_index.value = index
    }
    ElMessageBox.confirm('此操作将删除该组件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      autofocus: false,
    })
      .then(() => {
        deleteZj()
      })
      .catch(() => {})
  }
  const editBtn = (type: number, index: number) => {
    listArr_index.value = index
    show_module.value = true
    switch (type) {
      case 1:
        list_type.value = '编码组件'
        break
      case 2:
        list_type.value = '图片组件'
        break
      case 3:
        list_type.value = '文本组件'
        break
    }
  }
  // 纸张width
  watch(
    () => headerForm.value.width,
    (n) => {
      let max_W = []
      for (let index in elemDom.value) {
        max_W.push(Math.ceil(elemDom.value[index].offsetWidth / mm_px.value))
      }
      if (n < Math.max(...max_W)) {
        headerForm.value.width = Math.max(...max_W)
        ElMessage({
          type: 'warning',
          showClose: true,
          message: '宽度过小，请调整模块内容大小!',
          duration: 4000,
          offset: 100,
        })
      }
    },
  )
  //纸张height
  watch(
    () => headerForm.value.height,
    (n) => {
      let max_H = []
      for (let index in elemDom.value) {
        max_H.push(Math.ceil(elemDom.value[index].offsetHeight / mm_px.value))
      }
      if (n < Math.max(...max_H)) {
        headerForm.value.height = Math.max(...max_H)
        ElMessage({
          type: 'warning',
          showClose: true,
          duration: 4000,
          message: '高度过小，请调整模块内容大小!',
          offset: 200,
        })
      }
    },
  )
  const changeNum = (val: any, type: number) => {
    if (type == 1 && !val) {
      headerForm.value.width = 45
    }
    if (type == 2 && !val) {
      headerForm.value.height = 44
    }
    if (type == 4 && !val) {
      headerForm.value.paperSpacing = 1
    }
    if (type == 5 && !val) {
      headerForm.value.rowQty = 1
    }
  }
  // 改变数量
  const changeTotal = (val: string | number) => {
    if (headerForm.value.codeNum == 0 || val == '') {
      headerForm.value.codeNum = 1
      val = 1
    }
  }
  const paramsId: any = ref('')
  onMounted(() => {
    paramsId.value = route.params.id
    // 重置 store 数据为初始值
    codeStore.$reset()
    //单位转换
    // 创建一个1mm宽的元素插入到页面，然后坐等出结果
    const div = document.createElement('div')
    div.id = 'mm'
    div.style.width = '1mm'
    document.querySelector('body').appendChild(div)
    const mm1 = document.getElementById('mm').getBoundingClientRect() // 原生方法获取浏览器对元素的计算值
    mm_px.value = mm1.width

    if (route.params.id != '1') {
      //判断是新建1 还是详情
      loading.value = true
      printTemplateGetDetail(route.params.id).then((res) => {
        loading.value = false
        if (res.data.success) {
          let tmp = _.cloneDeep(res.data.data.row)
          delete tmp.templateComponentVos
          headerForm.value = { ...headerForm.value, ...tmp }
          headerForm.value.status = !headerForm.value.status
          componenTemplate.value = res.data.data.row.templateComponentVos
        } else {
          if (res.data.isError)
            ElMessage({
              type: 'error',
              showClose: true,
              message: res.data.message,
              duration: 4000,
              offset: 100,
            })
        }
      })
    }
  })
  const arry = ref([])
  //保存
  const btnSave = async () => {
    if (headerForm.value.name == '') {
      ElMessage({
        type: 'warning',
        showClose: true,
        message: '请输入名称!',
        offset: 100,
      })
      return
    }
    arry.value = []
    // 遍历处理
    for (let index in componenTemplate.value) {
      let tmpItem = []
      for (let key in componenTemplate.value[index].components) {
        let j = componenTemplate.value[index].components[key]
        let img = j.image
        if (j.tmpImg) {
          //做一个判断是本地上传的
          if (j.image.length > 0) {
            //判断是否有图片
            let tmpimg = j.tmpImg
            delete j.tmpImg // 删除
            await codeUpload([tmpimg.raw!]).then((res) => {
              // 提交图片，获取后端处理的图片路径 替换
              img = res.data.data.rows[0]
            })
          }
        }
        tmpItem.push({ ...j, image: img })
      }
      arry.value.push({ ...componenTemplate.value[index], components: tmpItem })
    }
    let dataObj = _.cloneDeep(headerForm.value)
    dataObj.status = !dataObj.status
    // 获取处理好的数据并提交请求
    onSave({ ...dataObj, templateComponentVos: arry.value })
  }
  // 保存提交请求
  const onSave = (data) => {
    savePrintTemplate(data).then((res) => {
      if (res.data.success) {
        ElMessage({
          type: 'success',
          showClose: true,
          message: res.data.message,
          offset: 100,
        })
        if (imgListDelete.value.length > 0) {
          deleteFile(imgListDelete.value)
        }
        TagsViewStore.delView(router.currentRoute.value.path)
        router.push('/code/printtemp')
      } else {
        if (res.data.isError)
          ElMessage({
            type: 'error',
            showClose: true,
            message: res.data.message,
            duration: 4000,
            offset: 100,
          })
      }
    })
  }
  // 刷新页面
  const refresh = () => {
    useSetting.setReload()
  }
  // 拖动
  const move = (e, index: number, type: any) => {
    show_module.value = true
    listArr_index.value = index
    let odiv = e.currentTarget //获取目标元素
    let e_ = e
    switch (type) {
      case 1:
        list_type.value = '编码组件'
        break
      case 2:
        list_type.value = '图片组件'
        break
      case 3:
        list_type.value = '文本组件'
        break
    }
    //算出鼠标相对元素的位置
    let disX = e.clientX - odiv.offsetLeft
    let disY = e.clientY - odiv.offsetTop
    e_.target.style.cursor = 'move'
    document.onmousemove = (e) => {
      //鼠标按下并移动的事件
      //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
      let left = e.clientX - disX
      let top = e.clientY - disY
      if (left > headerForm.value.width * mm_px.value - e_.target.style.width.slice(0, -2)) {
        odiv.style.left =
          headerForm.value.width * mm_px.value - e_.target.style.width.slice(0, -2) + 'px'
        componenTemplate.value[boxIndex.value].components[index].coordinateX =
          headerForm.value.width * mm_px.value - e_.target.style.width.slice(0, -2)
      } else {
        if (left <= 0) {
          componenTemplate.value[boxIndex.value].components[index].coordinateX = 0
          return
        }
        odiv.style.left = left + 'px'
        componenTemplate.value[boxIndex.value].components[index].coordinateX = left
      }
      if (top > headerForm.value.height * mm_px.value - e_.target.style.height.slice(0, -2)) {
        odiv.style.top =
          headerForm.value.height * mm_px.value - e_.target.style.height.slice(0, -2) + 'px'
        componenTemplate.value[boxIndex.value].components[index].coordinateY =
          headerForm.value.height * mm_px.value - e_.target.style.height.slice(0, -2)
      } else {
        odiv.style.top = top + 'px'
        componenTemplate.value[boxIndex.value].components[index].coordinateY = top
      }
      //改变元素位置属性值，移动当前元素
    }
    document.onmouseup = (e) => {
      // 鼠标松开后不再移动
      document.onmousemove = null
      document.onmouseup = null
    }
    //阻止拖拽的默认行为,比如图片会先拖出影子，最后在改变位置，会出现禁止拖拽的标志

    document.ondragstart = function () {
      return false
    }
  }
  // 选择父元素
  const selectBox = (e: { target: any; currentTarget: any }, index: number) => {
    boxIndex.value = index
    if (e.target == e.currentTarget) {
      listArr_index.value = 0
      show_module.value = false
    }
    if (componenTemplate.value.length == 0) {
      show_module.value = false
    }
    if (menu.value) {
      menu.value.open(index)
    }
  }
  // 取消选中
  const clearSelect = () => {
    boxIndex.value = -1
    listArr_index.value = -1
    show_module.value = false
    document.ondragstart = function () {
      return true
    }
  }
  // 添加组件
  const add = (type: number) => {
    if (boxIndex.value == -1) {
      ElMessage({
        type: 'warning',
        showClose: true,
        message: '请选择要加入到哪个纸张模块',
        duration: 4000,
        offset: 100,
      })
      return
    }
    show_module.value = false
    let item = {}
    if (type == 1) {
      item = JSON.parse(JSON.stringify(item1.value))
    } else if (type == 2) {
      item = JSON.parse(JSON.stringify(item2.value))
    } else if (type == 3) {
      item = JSON.parse(JSON.stringify(item3.value))
    }
    componenTemplate.value[boxIndex.value].components.push(item)
  }
</script>

<style scoped lang="scss">
  @import './blank.scss';

  .image-slot_xy {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
  }

  .image-slot_xy .el-icon {
    font-size: 30px;
  }
</style>
